package org.sample.controller;

import org.sample.commons.lang.RandomUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@Controller
public class FileUploadController {

    @Value("${upload-file.pattern}")
    private String pattern;

    @Value("${upload-file.location}")
    private String location;

    @RequestMapping(value = "upload", consumes = "multipart/form-data", method = RequestMethod.POST)
    public void upload(@RequestParam("uploadFile") MultipartFile multipartFile, String callbackId, HttpServletResponse response) throws Exception {
        LocalDate date = LocalDate.now();
        String today = date.format(DateTimeFormatter.BASIC_ISO_DATE);

        String filePath = location + today;
        File dir = new File(filePath);
        dir.mkdir();

        String ordFileName = multipartFile.getOriginalFilename();
        String suffix = ordFileName.substring(ordFileName.lastIndexOf("."));
        String fileName = System.currentTimeMillis() + RandomUtils.nextString(4) + suffix;

        FileOutputStream fos = new FileOutputStream(new File(dir, fileName));
        fos.write(multipartFile.getBytes());
        fos.close();

        String fileUrl = pattern + today + "/" + fileName;
        response.getWriter().println("<script>parent.callback('" + callbackId + "', '" + fileUrl + "')</script>");
    }
}